import React, {useContext, useEffect, useState} from 'react';
import {Modal, Button, message, Input, Row, Col, Space, Avatar, Popover, Radio, Popconfirm} from 'antd';
import style from './index.module.css';
import {
    EyeInvisibleOutlined,
    EyeOutlined,
    GlobalOutlined, LikeOutlined, SendOutlined, SmileFilled, SmileTwoTone,
} from "@ant-design/icons";
import {PostContext} from "../../indexMain/index";
import AliyunOSSUpload from "../AliyunOSSUpload";
import {Emoji} from "./emoji";
import {post} from "../../../utils/post";
const { TextArea } = Input;

export function PostMessage(props) {
    const [loading, changeLoading] = useState(false);
    const [reply,changeReply] = useState(0)
    const [imgData,setImgData]=useState([])
    const [value,setValue]=useState('');
    const [showEmoji,setShowEmoji]=useState(false)
    const {mypost,setPost} = useContext(PostContext)
    const IconTable =[<GlobalOutlined/>,<LikeOutlined />,<EyeOutlined />,<EyeInvisibleOutlined />]
    const msg =['允许查看、点赞、评论','仅查看、点赞，不允许评论','只允许查看','私密分享']
    const rights=['ALLOW','CANT_COMMENT','ONLY_VIEW','NO_VIEW']
    useEffect(()=>{
        if(props.editContent!==undefined){
            setValue(props.editContent.content);
            setImgData(props.editContent.images);
        }
    },[props.show])
    //修改分享范围
    const changeReplyContent=()=>{
        return(
            <>
                <Radio.Group onChange={onChangeReply} value={reply}>
                    <Space direction="vertical">
                        {
                            IconTable.map((item,key)=>{
                                return (
                                    <Radio key={key} value={key}>
                                        {item}
                                        {msg[key]}
                                    </Radio>
                                )
                            })
                        }
                    </Space>
                </Radio.Group>
            </>
        )
    }
    //修改分享范围
    const onChangeReply = e =>{
        // console.log('radio checked', e.target.value);
        changeReply(e.target.value)
    }
    //发送
    const handleOk = async () => {
        const token = localStorage.getItem('TOKEN');
        const {nickname,avatar}=JSON.parse(localStorage.getItem('USERDATA'))
        if (!value)
            message.error('请输入一点东西吧~')
        else {
            //发送分享
            if(props.editContent===undefined){
                changeLoading(true)
                console.log(rights[reply],"reply");
                const res=await post('/share',{
                    content:value,
                    imageUrls:imgData?imgData:[],
                    sharePostStatusEnum:rights[reply]
                },token)
                if(res.data.code===0){
                    const {createTime,shareId}=res.data.data;
                    const newItem = {
                            avatar,
                            commentCount:0,
                            content:value,
                            createTime,
                            images:imgData,
                            likeCount:0,
                            nickname,
                            shareId:shareId,
                            updateTime:createTime
                        }
                        setPost(newItem);
                        setValue("");
                        setImgData([]);
                    }
                else{
                    message.error(res.data.errorMsg);
                }
                changeLoading(false);
                props.changeShow(false);
            }
            //修改推文
            else {
                let shareId=props.editContent.shareId;
                changeLoading(true);
                const res=await post(`/share/${shareId}/update`,{
                    content:value,
                    imageUrls:imgData?imgData:[],
                    sharePostStatus:rights[reply]
                },token)
                if(res.data.code===0)
                {
                    message.success('修改成功')
                    props.update(props.page);
                }
                else message.error('修改失败')
                changeLoading(false)
                props.changeShow(false);
            }
        }
    };
    const handleCancel = () => {
        setTimeout(() => {
            props.changeShow(false);
        }, 0);

    };
    const onChange = (e) => {
        setValue(e.target.value);
    };
    const showInfo = () => {
        const avatar = JSON.parse(localStorage.getItem("USERDATA"))?.avatar;
        return (
            <>
                <Avatar src={avatar}  />
                <p className={`${style.title}`}>今天我也开摆了</p>
            </>
        )
    }
    const addEmoji=(emoji)=>{
        setValue(value+emoji);
        setShowEmoji(false)
    }
    const changeImgList = (array)=>{
        // console.log(array,"现在是个什么玩意儿")
        let urlArray = array.map(item=>{
            if(typeof item === 'string')
            return item;
            else return 'http://baiblog.oss-cn-guangzhou.aliyuncs.com/'+item.url
        })
       setImgData([...urlArray]);
    }
    const content = () => {
        return (
            <>
                <TextArea
                    className={`${style.input}`}
                    placeholder="说点什么...."
                    maxLength={300}
                    showCount={true}
                    value = {value}
                    onChange={(e)=>onChange(e)}
                />
                <Popover placement="bottom" title={'选择分享范围'} content={changeReplyContent} trigger="click">
                    <Button className={`${style.type}`} type="primary" shape="round" icon={IconTable[reply]} size="small">
                        {msg[reply]}
                    </Button>
                </Popover>
                <Row className={`${style.bottom}`}>
                    <Col span={8} >
                        <div className={style.action}>
                            <SmileFilled className={style.smile} onClick={()=>setShowEmoji(true)} />
                            <AliyunOSSUpload value={imgData} changeImgList={(data)=>changeImgList(data)}/>
                        </div>
                    </Col>
                    <Col span={8} offset={8}>
                        <Button type="primary" icon={<SendOutlined />} shape="round" onClick={handleOk} loading={loading} style={{ float: 'right' }}>
                            发送
                        </Button>
                    </Col>
                </Row>
            </>
        )
    }
    return (
        <>
            <Modal
                style={{ position: 'absolute', left: '35%', height: '400px' }}
                bodyStyle={{ height: '400px' }}
                width={600}
                visible={props.show}
                onCancel={handleCancel}
                footer={null}
                mask={false}
            >
                {
                    showInfo()
                }{
                    content()
                }
            </Modal>
            <Modal
                   width={420}
                   visible={showEmoji}
                   closable={false}
                   footer={null}
                   mask={false}
                   onOk={handleOk}
                   onCancel={()=>{setShowEmoji(false);}}>
                <div className={style.emoji}>
                    {
                        Emoji.map(item=>{
                            return  <span className={style.emojiItem} onClick={()=>addEmoji(item.emoji)} key={item.id}>{item.emoji}</span>
                        })
                    }
                </div>
            </Modal>
        </>

    );
}

